package io.renren.socket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.renren.common.utils.Constant;
import io.renren.common.utils.StringUtils;
import io.renren.modules.substation.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DecodeIEC104JSON {
    public static Logger logger = LoggerFactory.getLogger(DecodeIEC104JSON.class);

    public static String numToHex16(int b) {
        return String.format("%04x", b);
    }
//遥信：
//0. 烟感告警
//1. 水浸告警
//2. 双鉴告警
//3. 1#防区入侵告警
//4. 1#低电量告警
//5. 2#防区入侵告警
//6. 2#低电量告警
//遥测
//0.1#温度
//1.1#湿度
//2.1#SF6浓度
//3.1#O2浓度

//    02版101：
//    遥信∶信息对象地址范围为1H~1000H。
//    继电保护1∶信息对象地址范围为1001H~2000H，对应带CP56Time2a时标的继电保护设备事件、带CP56Time2a时标的继电保护设备成组启动事件、带CP56Time2a时标的继电保护设备成组输出电路信息。
//    继电保护2∶信息对象地址范围为2001H~3000H，为继电保护动作的故障电流区。
//    继电保护3∶信息对象地址范围为3001H~4000H，为继电保护定值设定区。
//    遥测∶信息对象地址范围为4001H~5000H。
//    参数地址范围为5001H~6000H。
//    遥控、升降地址范围为6001H~6200H.
//    设点 6201H~6400H
//    电度 6401H~6600H

    public static void sendJsonResMsg(JSONObject obj, ChannelHandlerContext ctx) {

        try {
//            String msg = JSONObject.toJSONString(obj);
            String objStr = obj.toJSONString();
            logger.debug("104-应答jsonStr:" + objStr);
//            String escstr = StringEscapeUtils.unescapeJava(objStr);
//            logger.debug("s-应答escstr:" + escstr);
            String Unistr = StringUtils.decodeUnicode(objStr);
            logger.debug("104-应答Unistr:" + Unistr);
            String unstr = StringUtils.convertUnicodeToCh(objStr);
            logger.debug("104-应答unstr:" + unstr);
            String msgstrH = StringUtils.toChineseHex(objStr);
            String jsonSize = String.format("%08X", msgstrH.length() / 2);
            String header = "FFFFFFFF" + jsonSize;
            logger.debug("104-header + msgstrH:" + header + msgstrH);
            ctx.channel().writeAndFlush(header + msgstrH);
        } catch (Exception e) {
            logger.error("104-sendJsonResMsg error： " + e);
        }
    }

    //104协议解析
    public static void decodeiec104json(ServerHandler serverHandler, JSONObject obj, ChannelHandlerContext ctx) {
        try {
            String stationadevcod = obj.getString("从站编码");
            String stationaddress = obj.getString("从站地址");

            TBusiDevStatusInfoEntity tBusiDevStatusInfoEntity = new TBusiDevStatusInfoEntity();
            tBusiDevStatusInfoEntity.setDevCode(stationadevcod);
//            tBusiDevStatusInfoEntity.setDevStatus("1");
            tBusiDevStatusInfoEntity.setIsVaild("1");
            tBusiDevStatusInfoEntity.setLastOpr((long) 0);
            tBusiDevStatusInfoEntity.setLastTime(new Date());
            int updsumSta = serverHandler.tBusiDevStatusInfoService.updateDevStatusInfoByCode(tBusiDevStatusInfoEntity);
            if(updsumSta <= 0){
                logger.debug("更新时间---检测动环设备状态不存在 编号["+stationadevcod+"]updsumSta["+updsumSta+"]");
            }

            boolean soTest = false;
            boolean soEffective = false;
            byte soAdd = 0;
            byte soTran = 0;

//            Constant.M_SP_TB_1;
            byte flagType = obj.getByte("类型标识");
            byte informationnum = obj.getByte("信息数量");
            JSONObject whyobj = obj.getJSONObject("传送原因");
            if (whyobj != null) {
                logger.debug("存在传送原因");
                soTest = whyobj.getBoolean("试验标志");
                soEffective = whyobj.getBoolean("有效标志");
                soAdd = whyobj.getByte("源发地址");
                soTran = whyobj.getByte("传送原因");
                logger.debug("存在传送原因-试验标志["+soTest+"]有效标志["+soEffective+"]源发地址["+soAdd+"]传送原因["+soTran+"]");
            }
            byte publicaddress = obj.getByte("公共地址");//链路地址
            JSONArray informationarray = obj.getJSONArray("信息体");
            logger.debug("信息体:" + informationarray);

            if ((Constant.M_SP_TB_1 < flagType && flagType < Constant.M_EP_TF_1) ||
                    Constant.M_SE_TA_1 < flagType && flagType < Constant.M_SE_TG_1) {
                JSONObject absolutetimescale = obj.getJSONObject("绝对时标");
                logger.debug("绝对时标" + absolutetimescale);
            }

            //通过设备地址获取设备信息
//            TInfoDevInfoEntity devinfoCondition = new TInfoDevInfoEntity();
//            devinfoCondition.setIpAddr(stationaddress);
//            TInfoDevInfoEntity devinfo = serverHandler.tInfoDevInfoService.queryDevInfoByCondition(devinfoCondition);
//            if(devinfo != null) {
//                devinfo.getDevCode();
//                logger.debug("信息2");
//            }
//            TRegisterPointInfoEntity tRegisterPointInfoEntity = new TRegisterPointInfoEntity();
//            List<TRegisterPointInfoEntity> tRegisterPointInfoEntityList = serverHandler.tRegisterPointInfoService.queryRegisterPointInfoListByCondition(tRegisterPointInfoEntity);
//            Map<String,TRegisterPointInfoEntity> mapP = null;
//            for(int l=0;l<tRegisterPointInfoEntityList.size();l++){
//                mapP.put(tRegisterPointInfoEntityList.get(l).getAddressStart()+tRegisterPointInfoEntityList.get(l).getAddressEnd(),tRegisterPointInfoEntityList.get(l));
//            }

//            TPpRegInfoEntity tPpRegInfoEntity = new TPpRegInfoEntity();
//            tPpRegInfoEntity.setAdderss();
//            serverHandler.tPpRegInfoService.queryRegInfoByCondition(tPpRegInfoEntity);

            for (int i = 0; i < informationarray.size(); i++) {
                JSONObject informationobj = informationarray.getJSONObject(i);

                int addr = informationobj.getIntValue("信息对象地址");
                logger.debug("信息对象地址:" + addr);
                if (addr == 0) {
                    String addrstr = informationobj.getString("信息对象地址");
                    logger.debug("信息对象地址:" + addrstr + "无地信息对象地址据丢弃");
                    continue;
                }
                int informationdata = informationobj.getIntValue("信息体数据");
                logger.debug("原始：信息体数据:" + informationdata);
                if (addr > 0 && addr <= 0x4000) {
                    logger.debug("属于遥测数据");
//                    String infodata = String.format("%08x", informationdata);
//                    Long l = parseLong(infodata, 16);
//                    Float f = Float.intBitsToFloat(l.intValue());
//                    logger.debug("STRING:" + infodata);
//                    logger.debug("LONG:" + l);
//                    logger.debug("FLOAT:" + f);
//                    logger.debug(Integer.toHexString(Float.floatToIntBits(f)));
//                    dataValue = informationdata
                }

                if( (flagType >= Constant.M_SC_NA_1 && flagType <= Constant.M_SE_ND_1) ||
                        (flagType >= Constant.M_SE_TA_1 && flagType <= Constant.M_SE_TG_1) ) {
                    String typeContry = informationobj.getString("遥控类型");
                    logger.debug("遥控类型:" + typeContry);
                    if (typeContry != null || typeContry != "") {
                        String addressstr = numToHex16(addr);
                        logger.debug("遥控摇调 点号:" + addressstr);
                        if (typeContry.equals("0")) { //遥控执行
                            logger.debug("遥控摇调执行应答:" + typeContry);

                        } else if (typeContry.equals("1")) {//遥控选择
                            logger.debug("遥控摇调选择应答:" + typeContry);
                            if (whyobj == null) {
                                logger.error("遥控摇调选择应答-传送原因为空");
                            }
                            resultControlCmd(obj, ctx);
                            continue;
                        } else {
                            logger.debug("非遥控遥调应答-但类型是遥控遥调");
                        }
                    }
                }

                boolean effectiveflag = informationobj.getBoolean("有效标志");
                logger.debug("有效标志:" + effectiveflag);
                if (!effectiveflag) {
                    logger.error("有效标志:" + effectiveflag + "无效丢弃");
                    continue;
                }
                boolean refreshflag = informationobj.getBoolean("刷新标志");
                logger.debug("刷新标志:" + refreshflag + " 不处理");
                boolean replaceflag = informationobj.getBoolean("取代标志");
                logger.debug("取代标志:" + replaceflag + " 不处理");
                boolean blockadeflag = informationobj.getBoolean("封锁标志");
                logger.debug("封锁标志:" + blockadeflag + " 不处理");

                String overflowflag = informationobj.getString("溢出标志");
                logger.debug("溢出标志:" + overflowflag);
                if ( (overflowflag != null && overflowflag.equals("true"))) {
                    logger.error("溢出标志:" + overflowflag + "溢出-无效丢弃");
                    continue;
                }
                int remotestatevalue = informationobj.getIntValue("遥信状态值");
                logger.debug("遥信状态值:" + remotestatevalue);
                String str = informationobj.getString("遥信状态值");
                logger.debug("遥信状态值:" + str);
                //入库前操作
//                if((informationdata & 0xFFFFFF) == 0xFFFFFF) {
//                    logger.debug("未测量:" + addr);
//                    continue;
//                }
                String addressstr = numToHex16(addr);
                String infodata = String.format("%08x", informationdata);
                logger.debug("点位信息 点号[" + addressstr + "] 值[" + infodata + "]");

                TPointInfoDataConfEntity tPointInfoDataConfEntity = new TPointInfoDataConfEntity();
                tPointInfoDataConfEntity.setLastOpr((long) 0);
                tPointInfoDataConfEntity.setLastTime(new Date());
                tPointInfoDataConfEntity.setAddPublic("" + publicaddress);
                tPointInfoDataConfEntity.setAddress("" + addressstr);
                tPointInfoDataConfEntity.setDevCode(stationadevcod);
                byte[] bya = StringUtils.hexStringToByteArray(infodata);
                Float ff = null;
                logger.debug("104-测试1");
                if (flagType == Constant.M_SP_NA_1 || flagType == Constant.M_DP_NA_1 || //单点双点不带时标
                        flagType == Constant.M_SP_TB_1 || flagType == Constant.M_DP_TB_1) { //单双带时标
                    logger.debug("104-测试2：" + remotestatevalue);
                    tPointInfoDataConfEntity.setTypeFl("0");
                    tPointInfoDataConfEntity.setDataInfo("" + remotestatevalue);
                    tPointInfoDataConfEntity.setDataValue("" + remotestatevalue);

                } else if (flagType == Constant.M_ME_NA_1 || flagType == Constant.M_ME_NB_1 ||
                        flagType == Constant.M_ME_NC_1 || flagType == Constant.M_DP_TB_1 || flagType == Constant.M_ME_ND_1 || //遥测不带时标
                        flagType == Constant.M_ME_TD_1 || flagType == Constant.M_ME_TE_1 ||
                        flagType == Constant.M_ME_TF_1 || flagType == Constant.M_ME_TF_1) { //遥测带时标
                    logger.debug("104-测试3");
                    tPointInfoDataConfEntity.setTypeFl("1");
                    ff = getFloat(bya);
                    tPointInfoDataConfEntity.setDataInfo("" + informationdata);
                    tPointInfoDataConfEntity.setDataValue("" + ff);
                } else {
//                    tPointInfoDataConfEntity.setTypeFl("1");
                    logger.debug("其他非遥测遥信类型：" + flagType);
                    tPointInfoDataConfEntity.setDataInfo("" + informationdata);
                    tPointInfoDataConfEntity.setDataValue("" + ff);
                }


                Date t = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                List<TPointInfoDataConfEntity> list = InitPointInfoDataConfService.cache.get("Point");
                logger.debug("104-测试4");
                TBusiDevMonitorInfoEntity tBusiDevMonitorInfoEntity = new TBusiDevMonitorInfoEntity();
                for (int ii = 0; ii < list.size(); ii++) {
//                    TPointInfoDataConfEntity;
                    if (list.get(ii).getTypeFl().equals(tPointInfoDataConfEntity.getTypeFl()) &&
                            list.get(ii).getAddPublic().equals(tPointInfoDataConfEntity.getAddPublic()) &&
                            list.get(ii).getDevCode().equals(tPointInfoDataConfEntity.getDevCode()) &&
                            list.get(ii).getAddress().equals(tPointInfoDataConfEntity.getAddress())) {
//                        list.get(ii).getCoefficient();
//                        list.get(ii).getOffsets();
                        if (list.get(ii).getIsCad().equals("1")) {
                            float vaule = Float.valueOf(tPointInfoDataConfEntity.getDataValue());
                            tPointInfoDataConfEntity.setDataValue("" + vaule * list.get(ii).getCoefficient() + list.get(ii).getOffsets());
                            list.get(ii).setDataValue(tPointInfoDataConfEntity.getDataValue());
                        } else {
                            logger.debug("该条数据非系数偏移");
                        }

                        int updsum = serverHandler.tPointInfoDataConfService.updateByAddAndType(tPointInfoDataConfEntity);
                        if (updsum <= 0) {
                            logger.debug("该条无数据匹配更新动力环设备点表-丢弃");
                            logger.debug("list:TypeFl[" + list.get(ii).getTypeFl()+"]AddPublic["+list.get(ii).getAddPublic()+"]DevCode["+list.get(ii).getDevCode()+"]Address["+list.get(ii).getAddress());
                            logger.debug("Enti:TypeFl[" + tPointInfoDataConfEntity.getTypeFl()+"]AddPublic["+tPointInfoDataConfEntity.getAddPublic()+"]DevCode["+tPointInfoDataConfEntity.getDevCode()+"]Address["+tPointInfoDataConfEntity.getAddress());
                        }
                    } else {
                        logger.debug("该条匹配失败未更新PointInfo匹配对象");
                        logger.debug("list:TypeFl[" + list.get(ii).getTypeFl()+"]AddPublic["+list.get(ii).getAddPublic()+"]DevCode["+list.get(ii).getDevCode()+"]Address["+list.get(ii).getAddress());
                        logger.debug("Enti:TypeFl[" + tPointInfoDataConfEntity.getTypeFl()+"]AddPublic["+tPointInfoDataConfEntity.getAddPublic()+"]DevCode["+tPointInfoDataConfEntity.getDevCode()+"]Address["+tPointInfoDataConfEntity.getAddress());
                        continue;
                    }

                    tBusiDevMonitorInfoEntity.setLastOpr((long) 0);
                    tBusiDevMonitorInfoEntity.setLastTime(new Date());
                    tBusiDevMonitorInfoEntity.setDevCode(list.get(ii).getDevCode());
                    logger.debug("list.get(i).getDevCode():" + list.get(ii).getDevCode());
                    logger.debug("list.get(i).getLastTime():" + list.get(ii).getLastTime());
                    //            tBusiDevMonitorInfoEntity.setMonitorTime("" + list.get(i).getLastTime());
                    int intstr = Integer.parseInt(list.get(i).getAddPublic());
                    String strDate = String.format("%02x", intstr);
                    if (list.get(ii).getTypeFl().equals("0")) {
                        tBusiDevMonitorInfoEntity.setVariableKind("00");
                        tBusiDevMonitorInfoEntity.setVariableValue(tPointInfoDataConfEntity.getDataValue());
                        tBusiDevMonitorInfoEntity.setVariableDesc(list.get(ii).getStatusTypeDesc());
//                        df.format(t);
                        if (tBusiDevMonitorInfoEntity.getVariableDesc().equals("红外双鉴")) {
                            logger.debug("红外双鉴值-为2时插入insertEventInfoBySystem，当前值："+tPointInfoDataConfEntity.getDataValue() +" 原："+tPointInfoDataConfEntity.getDataInfo());
                            if("2".equals(tPointInfoDataConfEntity.getDataInfo())) {
                                serverHandler.tBusiSysEventInfoService.insertEventInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), strDate + tBusiDevMonitorInfoEntity.getVariableDesc(), "红外双鉴事件");
                            }
                        } else {
                            logger.debug("遥信的值-为2时插入:insertAlarmInfoBySystem和insertEventInfoBySystem，当前值：" + tPointInfoDataConfEntity.getDataValue() + " 原："+tPointInfoDataConfEntity.getDataInfo());
                            if ("2".equals(tPointInfoDataConfEntity.getDataInfo())) {
                                logger.debug("遥信值是2 插入告警和事件");
                                serverHandler.tBusiSysAlarmInfoService.insertAlarmInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), strDate + tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableDesc() + "告警 值为:" + tPointInfoDataConfEntity.getDataInfo());
                                serverHandler.tBusiSysEventInfoService.insertEventInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), strDate + tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableDesc() + "事件 值为:" + tPointInfoDataConfEntity.getDataInfo());
                            }
                        }

                        if("1".equals(tPointInfoDataConfEntity.getDataInfo())){
                            logger.debug("遥信值原值为：" + tPointInfoDataConfEntity.getDataInfo());
                        }

                        int updatePoint = serverHandler.tInfoEfencePointService.updatePnByPostCode(tPointInfoDataConfEntity.getDevCode(),tPointInfoDataConfEntity.getAddress(),tPointInfoDataConfEntity.getDataInfo());
                        if( updatePoint > 0 ){
                            logger.debug("更新围住状态为:"+tPointInfoDataConfEntity.getDataInfo());
                        } else {
                            logger.debug("非围柱-不更新围住状态");
                        }

                    } else if (list.get(ii).getTypeFl().equals("1")) {
                        //去除环境量
//                        if(list.get(i).getAddPublic().equals("1")) {
//                            tBusiDevMonitorInfoEntity.setVariableKind("01");
//                        }else if(list.get(i).getAddPublic().equals("2")){
//                            tBusiDevMonitorInfoEntity.setVariableKind("02");
//                        }else if(list.get(i).getAddPublic().equals("3")){
//                            tBusiDevMonitorInfoEntity.setVariableKind("03");
//                        }else{
                            logger.debug("list.get(i).getTypeFl():" + list.get(ii).getTypeFl());
                            tBusiDevMonitorInfoEntity.setVariableKind("00");
//                            tBusiDevMonitorInfoEntity.setVariableValue(list.get(i).getDataValue());
//                        }
                        tBusiDevMonitorInfoEntity.setVariableValue(list.get(ii).getDataValue());
                        tBusiDevMonitorInfoEntity.setVariableDesc(list.get(ii).getStatusTypeDesc());
                        //                tBusiDevMonitorInfoEntity.setVariableStatus("0");
                    } else {
                        logger.debug("非遥信或遥测信号-不处理：" + list.get(ii).getTypeFl());
                        continue;
                    }

                    tBusiDevMonitorInfoEntity.setVariableValue2("0");
                    tBusiDevMonitorInfoEntity.setVariableValue3("0");

                    int updsum = serverHandler.tBusiDevMonitorInfoService.updateMonitorByCodeKindDesc(tBusiDevMonitorInfoEntity);
                    tBusiDevMonitorInfoEntity.setVariableValue2("0");
                    tBusiDevMonitorInfoEntity.setVariableValue3("0");
                    tBusiDevMonitorInfoEntity.setCreateOpr((long) 0);
                    tBusiDevMonitorInfoEntity.setCreateTime(new Date());
                    tBusiDevMonitorInfoEntity.setVariableStatus("0");
                    String codeStr = getVariableCodeByName(tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableKind(),serverHandler);
                    if (codeStr != null && codeStr != "") {
                        tBusiDevMonitorInfoEntity.setVariableCode(codeStr);
                    } else {
                        tBusiDevMonitorInfoEntity.setVariableCode(codeStr);
                        logger.debug("code值未配置：name:" + tBusiDevMonitorInfoEntity.getVariableDesc() + " kind:" + tBusiDevMonitorInfoEntity.getVariableKind());
                        continue;
                    }

                    tBusiDevMonitorInfoEntity.setMonitorTime(df.format(t));
                    if (updsum <= 0) {
                        serverHandler.tBusiDevMonitorInfoService.save(tBusiDevMonitorInfoEntity);
                    }

                    TBusiDevMonitorHisEntity tBusiDevMonitorHisEntity = new TBusiDevMonitorHisEntity();
                    BeanUtils.copyProperties(tBusiDevMonitorInfoEntity, tBusiDevMonitorHisEntity);
                    serverHandler.tBusiDevMonitorHisService.save(tBusiDevMonitorHisEntity);

                    String Key = tBusiDevMonitorInfoEntity.getDevCode() + "-" + tBusiDevMonitorInfoEntity.getVariableKind() + tBusiDevMonitorInfoEntity.getVariableDesc();
                    logger.debug("getCacheAlarmConfigInfo(Key)-key：" + Key);
                    TInfoAlarmConfigEntity tInfoAlarmConfigEntity = serverHandler.tInfoAlarmConfigService.getCacheAlarmConfigInfo(Key);
                    if (tInfoAlarmConfigEntity != null) {
                        logger.debug("Decoded当前值：" + tBusiDevMonitorInfoEntity.getVariableValue() + "，上下限:" + tInfoAlarmConfigEntity.getVariableMax() + "," + tInfoAlarmConfigEntity.getVariableMin());
//                        List<TBaseDictInfoEntity> listDict = serverHandler.tBaseDictInfoService.queryByDictKey("ALRAM_OUT_SWITCH");
//                        if(listDict.size() > 0 && listDict != null){
//                            logger.debug("告警外送是否启用:"+listDict.get(0).getDictValue());
//                        }
                        if (Float.valueOf(tBusiDevMonitorInfoEntity.getVariableValue()) > Float.valueOf(tInfoAlarmConfigEntity.getVariableMax())
                                || Float.valueOf(tBusiDevMonitorInfoEntity.getVariableValue()) < Float.valueOf(tInfoAlarmConfigEntity.getVariableMin())) {


                            String alarmType = "0";
                            if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("温度") >= 0 && Float.valueOf(tBusiDevMonitorInfoEntity.getVariableValue()) > Float.valueOf(tInfoAlarmConfigEntity.getVariableMax()))
                            {
                                alarmType = "1";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("温度") >= 0 && Float.valueOf(tBusiDevMonitorInfoEntity.getVariableValue()) < Float.valueOf(tInfoAlarmConfigEntity.getVariableMin())){
                                alarmType = "2";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("湿度") >= 0){
                                alarmType = "3";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("SF6") >= 0){
                                alarmType = "4";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("烟雾") >= 0){
                                alarmType = "5";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("水位") >= 0){
                                alarmType = "6";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("水泵") >= 0){
                                alarmType = "7";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("风机") >= 0){
                                alarmType = "8";
                            } else if(tBusiDevMonitorInfoEntity.getVariableDesc().indexOf("空调") >= 0){
                                alarmType = "9";
                            } else {
                                alarmType = "0";
                            }
                            AlarmSendingOutInfo alarmOutInfo = new AlarmSendingOutInfo();
                            alarmOutInfo.setDevCode(tBusiDevMonitorInfoEntity.getDevCode());
                            alarmOutInfo.setAlarmType(alarmType);
                            alarmOutInfo.setAlarmValue("2");

                            InitPointInfoDataConfService.cache2.put(tBusiDevMonitorInfoEntity.getDevCode() + tBusiDevMonitorInfoEntity.getVariableDesc(),alarmOutInfo);
                            logger.debug("外送告警:设备编号["+tBusiDevMonitorInfoEntity.getDevCode()+"]"+tBusiDevMonitorInfoEntity.getVariableDesc()+"["+alarmType+"]登记告警2");
                            runClientSendData.runNettyClient(alarmType,"2",tBusiDevMonitorInfoEntity.getDevCode());

                        } else {

                            logger.debug("未超过上下限阀值：cur["+tBusiDevMonitorInfoEntity.getVariableValue()+"]max["+tInfoAlarmConfigEntity.getVariableMax()+"]min["+tInfoAlarmConfigEntity.getVariableMin()+"]");
                            int updasu = serverHandler.tInfoAlarmConfigService.updateHealthStatus(Key, "0");
                            if (updasu <= 0) {
                                logger.debug("更新告警状态返回结果:" + updasu);
                            }

                            AlarmSendingOutInfo alarmOutInfo = InitPointInfoDataConfService.cache2.get(tBusiDevMonitorInfoEntity.getDevCode() + tBusiDevMonitorInfoEntity.getVariableDesc());
                            if(alarmOutInfo != null){
                                if(alarmOutInfo.getAlarmValue().equals("2")){
                                    logger.debug("外送取消告警:设备编号["+tBusiDevMonitorInfoEntity.getDevCode()+"]"+tBusiDevMonitorInfoEntity.getVariableDesc()+"["+alarmOutInfo.getAlarmType()+"]取消告警1");
                                    runClientSendData.runNettyClient(alarmOutInfo.getAlarmType(),"1",tBusiDevMonitorInfoEntity.getDevCode());

                                    alarmOutInfo.setAlarmValue("1");
                                    InitPointInfoDataConfService.cache2.put(tBusiDevMonitorInfoEntity.getDevCode() + tBusiDevMonitorInfoEntity.getVariableDesc(),alarmOutInfo);
                                }
                            }else{
                                logger.debug(tBusiDevMonitorInfoEntity.getVariableDesc()+"未找到告警记录无需外送告警");
                            }

                            continue;
                        }

                        logger.debug("超过上下限阀值更新告警:cur["+tBusiDevMonitorInfoEntity.getVariableValue()+"]max["+tInfoAlarmConfigEntity.getVariableMax()+"]min["+tInfoAlarmConfigEntity.getVariableMin()+"]");
                        int updasu = serverHandler.tInfoAlarmConfigService.updateHealthStatus(Key, "1");
                        if (updasu <= 0) {
                            logger.debug("更新告警状态返回结果:" + updasu);
                        }
                        serverHandler.tBusiSysAlarmInfoService.insertAlarmInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), strDate + tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableDesc() + "告警 值为:" + tBusiDevMonitorInfoEntity.getVariableValue());
                        serverHandler.tBusiSysEventInfoService.insertEventInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), strDate + tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableDesc() + "事件 值为:" + tBusiDevMonitorInfoEntity.getVariableValue());
                    } else {
                        logger.debug("未找到对应告警数据上下限");
                    }
                }

//                int updsum = serverHandler.tPointInfoDataConfService.updateByAddAndType(tPointInfoDataConfEntity);
//                if (updsum <= 0) {
//                    logger.debug("无数据匹配更新动力环设备点表-丢弃");
//                }

                logger.debug("动力环设备来的数据（暂保存旧表）");
                TPpRegInfoEntity tPpRegInfoEntity = new TPpRegInfoEntity();
                tPpRegInfoEntity.setAddress(addressstr);
                tPpRegInfoEntity.setAddValue(infodata);
                tPpRegInfoEntity.setEffective("" + effectiveflag);
                tPpRegInfoEntity.setAddSource("" + refreshflag);
                tPpRegInfoEntity.setTypeFl("" + flagType);
                tPpRegInfoEntity.setRemoCom("" + remotestatevalue);
                tPpRegInfoEntity.setAddPublic("" + publicaddress);
                tPpRegInfoEntity.setBlockAde("" + blockadeflag);
                tPpRegInfoEntity.setAddReplace("" + replaceflag);
                tPpRegInfoEntity.setOverFlow("" + overflowflag);
                tPpRegInfoEntity.setSoTest("" + soTest);
                tPpRegInfoEntity.setSoEffective("" + soEffective);
                tPpRegInfoEntity.setSoAdd("" + soAdd);
                tPpRegInfoEntity.setSoTran("" + soTran);
                logger.debug("信息10");
                if ((Constant.M_SP_TB_1 < flagType && flagType < Constant.M_EP_TF_1) ||
                        Constant.M_SE_TA_1 < flagType && flagType < Constant.M_SE_TG_1) {
                    JSONObject absolutetimescale = obj.getJSONObject("绝对时标");
                    if (absolutetimescale != null) {
                        boolean timeEffective = absolutetimescale.getBoolean("有效标志");
                        String timeStr = absolutetimescale.getString("时间");
                        tPpRegInfoEntity.setTimeEffective("" + timeEffective);
                        tPpRegInfoEntity.setTimeStr(timeStr);
                    }
                    logger.debug("绝对时标" + absolutetimescale);
                }

                tPpRegInfoEntity.setLastOpr((long) 0);
                tPpRegInfoEntity.setLastTime(new Date());
                logger.debug("更新数据库 tPpRegInfoEntity");
                int updnum = serverHandler.tPpRegInfoService.updateByAdd(tPpRegInfoEntity);
                boolean saveflag;
                if (updnum <= 0) {
                    tPpRegInfoEntity.setCreateOpr((long) 0);
                    tPpRegInfoEntity.setCreateTime(new Date());
                    logger.debug("保存数据库 tPpRegInfoEntity");
                    saveflag = serverHandler.tPpRegInfoService.save(tPpRegInfoEntity);
                    if (!saveflag) {
                        logger.error("保存数据库失败 decodeiec104json tPpRegInfoEntity");
                    }
                }
//                if(mapP.get(addressstr) != null) {
//                if( true ) {
//                    String statustype = "08";//mapP.get(addressstr+addressstr).getStatusType();
//                    String statustypeDesc = "无";//mapP.get(addressstr+addressstr).getStatusTypeDesc();
//                    logger.debug("寄存器地址：" + addressstr + " 类型：" + statustype + " 类型描述：" + statustypeDesc);
//                    switch (statustype) {
//                        case "01":
//                            decodetemperature(informationdata);
//                            break;
//                        case "02":
//                            decodehumidity(informationdata);
//                            break;
//                        case "03":
//                            decodeSF6concentration(informationdata);
//                            break;
//                        case "04":
//                            decodeoxygen(informationdata);
//                            break;
//                        default:
//                            logger.error("statustype error:" + statustype);
//                            break;
//                    }
//                }else{
//                    logger.error("addressstr 未配置" + addressstr);
//                }

//                int byte1 = informationdata & 0XFF;
//                int byte2 = (informationdata >> 8) & 0XFF;
            }
        } catch (Exception ex) {
            logger.error("decodeiec104json error： " + ex);
        }
    }
    //浮点型解析
    public static float getFloat(byte[] b) {
        int accum = 0;
        accum = accum|(b[3] & 0xff) << 0;
        accum = accum|(b[2] & 0xff) << 8;
        accum = accum|(b[1] & 0xff) << 16;
        accum = accum|(b[0] & 0xff) << 24;
        logger.debug("浮点型解析2:"+accum);
        return Float.intBitsToFloat(accum);
    }

    //浮点型解析
    public static float getFloatSM(byte[] b) {
        int accum = 0;
        accum = accum|(b[0] & 0xff) << 0;
        accum = accum|(b[1] & 0xff) << 8;
        accum = accum|(b[2] & 0xff) << 16;
        accum = accum|(b[3] & 0xff) << 24;
        logger.debug("浮点型解析:"+accum);
        return Float.intBitsToFloat(accum);
    }

    // int转换为byte[4]数组
    public static byte[] getByteArrayByInt(int i) {
        byte[] b = new byte[4];
        b[0] = (byte) ((i & 0xff000000) >> 24);
        b[1] = (byte) ((i & 0x00ff0000) >> 16);
        b[2] = (byte) ((i & 0x0000ff00) >> 8);
        b[3] = (byte)  (i & 0x000000ff);
        return b;
    }

    // int转换为byte[4]数组
    public static byte[] getByteArrayByIntSM(int i) {
        byte[] b = new byte[4];
        b[3] = (byte) ((i & 0xff000000) >> 24);
        b[2] = (byte) ((i & 0x00ff0000) >> 16);
        b[1] = (byte) ((i & 0x0000ff00) >> 8);
        b[0] = (byte)  (i & 0x000000ff);
        return b;
    }

    // float转换为byte[4]数组
    public static byte[] getByteArray(float f) {
        int intbits = Float.floatToIntBits(f);//将float里面的二进制串解释为int整数
        return getByteArrayByInt(intbits);
    }

    // 从byte数组的index处的连续4个字节获得一个int
    public static int getInt(byte[] arr, int index) {
        return 	(0xff000000 	& (arr[index+0] << 24))  |
                (0x00ff0000 	& (arr[index+1] << 16))  |
                (0x0000ff00 	& (arr[index+2] << 8))   |
                (0x000000ff 	&  arr[index+3]);
    }
    // 从byte数组的index处的连续2个字节获得一个int
    public static int getInt2(byte[] arr, int index) {
        return  (0x0000ff00 	& (arr[index+0] << 8))   |
                (0x000000ff 	&  arr[index+1]);
    }

    public static String getVariableCodeByName(String varName,String kind,ServerHandler serverHandler){
        String ret ="";
        TInfoVariableInfoEntity tInfoVariableInfoEntity = new TInfoVariableInfoEntity();
        tInfoVariableInfoEntity.setVariableKind(kind);
        List<TInfoVariableInfoEntity> VariableList = serverHandler.tInfoVariableInfoService.queryVariableByCondition(tInfoVariableInfoEntity);
        for(TInfoVariableInfoEntity o : VariableList){
            if(o.getVariableName().equals(varName))
            {
                ret=String.valueOf(o.getVariableId());
            }
        }
        return ret;
    }

    public static String resultControlCmd(JSONObject jobj,ChannelHandlerContext ctx)
    {
        JSONObject becauseobj = jobj.getJSONObject("传送原因");
        if(becauseobj != null) {
            logger.debug("修改传送原因-6");
            becauseobj.put("传送原因", 6);
            becauseobj.put("源发地址", 0);
            becauseobj.put("有效标志", true);
            becauseobj.put("试验标志", false);
        }

        jobj.put("传送原因",becauseobj);

        JSONArray infoArray = jobj.getJSONArray("信息体");
        if(infoArray != null){
            if(infoArray.size() > 1){
                logger.debug("遥控遥调选择应答-异常过量");
                return "";
            }
            JSONObject infoObj = infoArray.getJSONObject(0);
            String setvalue = infoObj.getString("设置值");
            if(setvalue != null || setvalue != ""){
                logger.debug("存在设置值："+setvalue);
            }else{
                logger.debug("不存在设置值");
            }
            infoObj.put("遥控类型",0);

//            infoArray.add(0,infoObj);
            jobj.put("信息体",infoObj);
        }


        logger.debug("遥控或遥调应答回："+jobj);
        sendJsonResMsg(jobj, ctx);
        return "ok";
//        return SendMsgToClent.sendJSONtoClent(setobj,Constant.AM_IEC104,devId,IP);
    }
//    {
//“从站编码”:string, //设备节点编码
//            "从站地址":string, //IP地址—⾮必须
//            "协议类型":byte, //0x00—104协议， 0x01—私有协议
//        "类型标识":byte,
//        "信息对象地址":int或者int[], //只有类型标志为136才是数组
//        "遥控类型":byte,
//        "输出⽅式":byte,
//        "设置值":byte或者byte[], //只有类型标志为136才是数
//  }

    /**
     *
     * @param devId     设备编号
     * @param controlType 控制类型，2-(双点)遥控：开、关这种   3-遥调： 温度调到 25。5度 这种（暂定） 4-单点遥控
     * @param addPublic  公共地址（可以和其他信息表的kind匹配，空调的可能也是） 00，01，02 转成 0，1，2 传入
     * @param typeDesc  描述（温度，湿度，SF6...）
     * @param Vaule  传输值（空值时传输缓存的值）
     * @param array  可能有类似空调的设备：空调模式1，空调模式2，空调模式3，属于空调的整体，可能存在整体上传需要传整体数组
     *               [
     *                  {
     *                      "devId":"中央空调",
     *                      "addPublic":"0",
     *                      "typeDesc":"空调模式1"
     *                      "Vaule":"null"
     *                  },
     *                  {
     *                      "devId":"中央空调",
     *                      "addPublic":"0",
     *                      "typeDesc":"空调模式2"
     *                      "Vaule":"36.5"
     *                  }
     *               ]
     * @return
     */
    public static String remoteControl(String controlType,String devId,String addPublic,String typeDesc,String Vaule,JSONArray array){

        logger.debug("controlType["+controlType+"]devId["+devId+"]addPublic["+addPublic+"]typeDesc["+typeDesc+"]Vaule["+Vaule+"]array["+array+"]");
        byte am=0;
        byte type=1;
        byte outputway=0;
        int infoAddr=0;
        int infoVlue=0;
        int point = 0;
        byte value[] = {};
        String IP = "";
        JSONArray arrinfo = new JSONArray();
        JSONArray arrvalue = new JSONArray();

        if(controlType.equals("2")){
            am = Constant.M_DC_NA_1;
            logger.debug("双点遥控["+controlType+"]am["+am+"]");
        } else if(controlType.equals("3")) {
            am = Constant.M_SE_NA_1;
            logger.debug("整数遥调["+controlType+"]am["+am+"]");
        } else if(controlType.equals("4")) {
            am = Constant.M_SC_NA_1;
//            controlType = "2";
            logger.debug("单点遥控["+controlType+"]am["+am+"]");
        } else {
            am = Constant.M_SE_NC_1;//其它-测试
            logger.debug("浮点遥调["+controlType+"]am["+am+"]");
//            controlType = "3";
        }

        List<TPointInfoDataConfEntity> list = InitPointInfoDataConfService.cache.get("Point");
        if(array == null)
        {
            logger.debug("单个点设备控制");
            if(list.size()<=0){
                logger.debug("未加载完缓存列表");
                return "null缓存";
            }

            for (int i = 0; i < list.size(); i++)
            {
                if( devId.equals(list.get(i).getDevCode()) &&
                        addPublic.equals(list.get(i).getAddPublic()) &&
                        typeDesc.equals(list.get(i).getStatusTypeDesc()) &&
                        controlType.equals(list.get(i).getTypeFl()) )
                {
                    logger.debug("第"+i+"次");
                    logger.debug(list.get(i).getDevCode());
                    logger.debug(list.get(i).getAddPublic());
                    logger.debug(list.get(i).getStatusTypeDesc());
                    logger.debug(list.get(i).getTypeFl());

                        byte address[] = StringUtils.hexStringToByteArray(list.get(i).getAddress());
                        logger.debug("" + address);
                        infoAddr = getInt2(address,0);
//                        byte value[];
                        value = null;
                        if(Vaule != null){
                            value = getByteArray(Float.parseFloat(Vaule));
                        } else {
                            value = getByteArray(Float.parseFloat(list.get(i).getDataValue()));
                        }

                        if(controlType.equals("2")){
                            logger.debug("遥控:"+Vaule);
                            infoVlue = Integer.parseInt(Vaule);
//                            value[0] = (byte) infoVlue;
                        }else if(controlType.equals("3")){
                            logger.debug("遥调:"+Vaule);
                            infoVlue = Integer.parseInt(Vaule);

                        } else if(controlType.equals("4")){
                            logger.warn("双点遥控（未测试）:"+Vaule);
                            infoVlue = Integer.parseInt(Vaule);
//                            return "未测试";
                        } else if(controlType.equals("5")){
                            logger.warn("双点遥调(未测试):"+Vaule);
                            infoVlue = getInt(value,0);
//                            return "未测试";
                        } else {
                            logger.error("非遥控遥调:"+Vaule);
                            return "非遥控遥调";
                        }
                    list.get(i).setDataValue(""+infoVlue);
//                    int updsum = serverHandler.tPointInfoDataConfService.updateByAddAndType(tPointInfoDataConfEntity);
//                    if (updsum <= 0) {
//                        logger.debug("无数据匹配更新动力环设备点表-丢弃");
//                    }

                    point++;
                }
            }
        } else {
            logger.debug("多个点设备控制");
            if(list.size()<=0){
                logger.debug("未加载缓存列表");
                return "未加载缓存列表";
            }
            for(int i=0;i<array.size();i++){
                logger.debug("第"+i+"个");
                for(int j=0;j<list.size();j++){
                    Object oobj = array.get(i);
                    JSONObject obj = (JSONObject) JSONObject.parse(oobj.toString());
                    String odevId = obj.getString("devId");
                    String oaddPublic = obj.getString("addPublic");
                    String otypeDesc = obj.getString("typeDesc");
                    String oVaule = obj.getString("Vaule");

                    if( odevId.equals(list.get(j).getDevCode()) &&
                            oaddPublic.equals(list.get(j).getAddPublic()) &&
                            otypeDesc.equals(list.get(j).getStatusTypeDesc()) &&
                            controlType.equals(list.get(j).getTypeFl()) )
                    {
                        logger.debug("第" + i +"次" + j);
                        devId = list.get(j).getDevCode();
                        addPublic = list.get(j).getAddPublic();
                            byte address[] = StringUtils.hexStringToByteArray(list.get(j).getAddress());
                            if (address.length < 2) {
                                return "遥控摇调电表地址配置错误";
                            }
                            infoAddr = getInt2(address,0);

                            arrinfo.add(infoAddr);

                            value = null;

                            if(oVaule != null){
                                value = getByteArray(Float.parseFloat(oVaule));
                            } else {
                                value = getByteArray(Float.parseFloat(list.get(j).getDataValue()));
                            }
//                            infoVlue = getInt(value,0);
                            if(controlType.equals("2")){
                                logger.debug("遥控:"+oVaule);
                                infoVlue = Integer.parseInt(oVaule);
//                                value[0] = (byte) infoVlue;
                            }else if(controlType.equals("3")){
                                logger.debug("遥调:"+oVaule);
                                infoVlue = Integer.parseInt(oVaule);
                            }else if(controlType.equals("4")){
                                logger.debug("双点遥控(未测试):"+oVaule);
//                                return "未测试";
                            } else if(controlType.equals("5")){
                                logger.debug("双点遥调(未测试):"+oVaule);
                                infoVlue = getInt(value,0);
//                                return "未测试";
                            } else {
                                logger.error("非遥控遥调:"+oVaule);
                                return "非遥控遥调";
                            }
                            list.get(i).setDataValue(""+infoVlue);
                            arrvalue.add(infoVlue);
//                        } else if(controlType.equals('3')){
//
//                        }
                        point++;
                    }
                }
            }
        }
        if(infoAddr == 0 && arrinfo == null){
            logger.debug("发送失败：至少要有1个地址");
            return "发送失败：至少要有1个地址";
        }else if(point == 0){
            logger.debug("发送失败：未配置地址");
            return "发送失败：未配置地址";
        }

        return remoteControlCmd( addPublic,am, devId, IP, infoAddr, infoVlue, type, outputway,arrinfo,arrvalue);
    }
//    //遥控遥调
    public static String remoteControlCmd(String addPublic,byte am ,String devId,String IP,int infoAddr,int infoVlue,byte type,byte outputway,JSONArray arrinfo,JSONArray arrvalue)
        {

            JSONObject setobj = new JSONObject();
        try {
//            setobj.put("从站地址", IP);//IP地址
            JSONArray arrayson = new JSONArray();
            JSONObject ooabj = new JSONObject();
            logger.debug("remote-devId:"+devId);
            setobj.put("从站编码", devId);
            logger.debug("remote-am:"+am);
            setobj.put("类型标识", am);
            logger.debug("remote-addPublic:"+addPublic);
            setobj.put("公共地址",Integer.parseInt(addPublic));
            if (arrinfo.size() > 1 && arrvalue.size() > 1) {
//                if (arrinfo.size() != arrvalue.size()) {
//                    logger.debug("信息对象地址 与 信息值长度不匹配");
//                    return "信息对象地址 与 信息值不匹配";
//                }
                for(int i=0;i<arrinfo.size();i++) {
                    logger.debug("remote-arrinfo:"+arrinfo.getIntValue(i));
                    ooabj.put("信息对象地址", arrinfo.getIntValue(i));
                    logger.debug("remote-arrvalue:"+arrvalue.getIntValue(i));
                    ooabj.put("设置值", arrvalue.getIntValue(i));
                    logger.debug("remote-type:"+type);
                    ooabj.put("遥控类型", type);
                    logger.debug("remote-outputway:"+outputway);
                    ooabj.put("输出方式", outputway);

//                    logger.debug("remote-测试有效标志false");
//                    ooabj.put("有效标志", false);
//                    ooabj.put("封锁标志", false);
//                    ooabj.put("取代标志", false);
//                    ooabj.put("刷新标志", true);

                    arrayson.add(ooabj);
                }
//                setobj.put("信息对象地址", arrinfo);
//                setobj.put("设置值", arrvalue);
                setobj.put("信息体", arrayson);
            } else {
//                setobj.put("信息对象地址", infoAddr);
//                setobj.put("设置值", infoVlue);
                logger.debug("remote-测试infoAddr"+infoAddr);
                ooabj.put("信息对象地址", infoAddr);
                logger.debug("remote-测试infoVlue"+infoVlue);
//                JSONArray valueArray = new JSONArray();
//                for(int v=0;v < value.length;v++){
//                    valueArray.add(value[v]);
//                }

                if(am == Constant.M_SC_NA_1 || am == Constant.M_DC_NA_1 || am == Constant.M_RC_NA_1 ||
                        am == Constant.M_SE_TA_1 || am == Constant.M_SE_TB_1 || am == Constant.M_SE_TC_1) {
                    logger.debug("遥控:"+infoVlue);
                    ooabj.put("设置值", infoVlue);
                }
                else if( am == Constant.M_SE_NC_1 || am == Constant.M_SE_TF_1) {
                    logger.debug("遥调:"+infoVlue);
                    byte[] infobytes = getByteArrayByIntSM(infoVlue);
                    JSONArray valueArray = new JSONArray();
                    for(int v=0;v < infobytes.length;v++){
                        valueArray.add(infobytes[v]);
                    }
                    ooabj.put("设置值", valueArray);
                } else if( am == Constant.M_SE_NA_1 || am == Constant.M_SE_TD_1) {
//                    int int20448 = getInt(value,0);
                    logger.debug("遥调整数:" + infoVlue);
                    ooabj.put("设置值", infoVlue);
                } else {
                    logger.debug("其他浮点" + infoVlue);
                    ooabj.put("设置值", infoVlue);
                }



                logger.debug("remote-测试type"+type);
                ooabj.put("遥控类型", type);
                logger.debug("remote-测试outputway"+outputway);
                ooabj.put("输出方式", outputway);

//                logger.debug("remote-测试有效标志false");
//                ooabj.put("有效标志", false);
//                ooabj.put("封锁标志", false);
//                ooabj.put("取代标志", false);
//                ooabj.put("刷新标志", true);

                setobj.put("信息体",ooabj);
            }

        }catch(Exception e){
            logger.debug("remoteControl 数据格式不匹配 出错");
            return "数据格式不匹配";
        }
            JSONObject becauseobj = new JSONObject();
            becauseobj.put("传送原因",6);
            becauseobj.put("源发地址",0);
            becauseobj.put("有效标志",true);
            becauseobj.put("试验标志",false);

            setobj.put("传送原因",becauseobj);
            logger.debug("发送---");

//        obj.put("类型标识", Constant.M_SP_NA_1);
//        obj.put("信息对象地址", Constant.M_SP_NA_1);//只有类型标志为136才是数组
//        obj.put("遥控类型", Constant.M_SP_NA_1);
//        obj.put("输出⽅式", Constant.M_SP_NA_1);
//        obj.put("设置值", (byte) Constant.M_SP_NA_1);//只有类型标志为136才是数组
        return SendMsgToClent.sendJSONtoClent(setobj,Constant.AM_IEC104,devId,IP);
    }

    //解析-温度
    public static int decodetemperature(int infomt){
        logger.debug("temperature值:"+infomt);
        String temperatureStr = "";
//        高字节（温度高8位）单位：摄氏度
//        D7	D6	D5	D4	        D3	D2	D1	D0
//        1=正	温度值百位（BCD码）	温度值十位（BCD码）
//        低字节（温度低8位）
//        D7	D6	D5	D4	        D3	D2	D1	D0
//        温度值个位（BCD码）	        温度值十分位（BCD码）
        int byte1 = (infomt >> 8) & 0xFF;
        int byte2 = infomt & 0xFF;

        int hundredplac = (byte1 >> 4) & 0x07;
        int tenplac = byte1 & 0x0F;
        int onesplac = (byte2 >> 4) & 0x0F;
        int miplac = byte2 & 0x0F;

        float temperatureValue = hundredplac * 100 + tenplac * 10 + onesplac + miplac/10;

        if( (byte1 >> 7) == 1 ){
            temperatureStr = "" + temperatureValue;
        } else {
            temperatureStr = "-" + temperatureValue;
        }

        logger.debug("打印温度:"+temperatureStr);

        return 0;
    }
    //解析-湿度
    private static int decodehumidity(int infomt){
        logger.debug("humidity值:"+infomt);
        String humidityStr = "";
//        高字节（湿度高8位）单位：%RH
//        D7	D6	D5	D4	D3	D2	D1	D0
//        固定为0	湿度值十位（BCD码）
//        低字节（湿度低8位）
//        D7	D6	D5	D4	D3	D2	D1	D0
//        湿度值个位（BCD码）	湿度值十分位（BCD码）
        int byte1 = (infomt >> 8) & 0xFF;
        int byte2 = infomt & 0xFF;

        int hundredplac = (byte1 >> 4) & 0x0F;
        logger.debug("hundredplac固定值:"+ hundredplac);
        hundredplac = 0;
        int tenplac = byte1 & 0x0F;
        int onesplac = (byte2 >> 4) & 0x0F;
        int miplac = byte2 & 0x0F;

        float humidityValue = hundredplac * 100 + tenplac * 10 + onesplac + miplac/10;

        humidityStr = "" + humidityValue;

        logger.debug("打印湿度:"+humidityStr);

        return 0;
    }
    //解析-SF6浓度
    private static int decodeSF6concentration(int infomt) {
        logger.debug("SF6值:" + infomt);
        String SF6concentrationStr = "";
//    高字节（SF6浓度高8位）单位：ppm
//    D4	D3	D2	D1	D0
//    SF6浓度千位（BCD码）	SF6浓度百位（BCD码）
//    低字节（SF6浓度低8位）
//    D4	D3	D2	D1	D0
//    SF6浓度十位（BCD码）	SF6浓度个位（BCD码）
        int byte1 = (infomt >> 8) & 0xFF;
        int byte2 = infomt & 0xFF;

        int hundredplac = (byte1 >> 4) & 0x0F;
        int tenplac = byte1 & 0x0F;
        int onesplac = (byte2 >> 4) & 0x0F;
        int miplac = byte2 & 0x0F;

        float SF6concentrationValue = hundredplac * 1000 + tenplac * 100 + onesplac * 10 + miplac;
        SF6concentrationStr = "" + SF6concentrationValue;

        logger.debug("打印SF6浓度:"+SF6concentrationStr);
        return 0;
    }
    //解析-氧气浓度
    private static int decodeoxygen(int infomt) {
        logger.debug("oxygen值:" + infomt);
        String oxygenStr = "";
//    高字节（SF6浓度高8位）单位：ppm
//    D4	D3	D2	D1	D0
//    SF6浓度千位（BCD码）	SF6浓度百位（BCD码）
//    低字节（SF6浓度低8位）
//    D4	D3	D2	D1	D0
//    SF6浓度十位（BCD码）	SF6浓度个位（BCD码）
        int byte1 = (infomt >> 8) & 0xFF;
        int byte2 = infomt & 0xFF;

        int hundredplac = (byte1 >> 4) & 0x0F;
        logger.debug("hundredplac固定值:"+ hundredplac);
        hundredplac = 0;
        int tenplac = byte1 & 0x0F;
        int onesplac = (byte2 >> 4) & 0x0F;
        int miplac = byte2 & 0x0F;

        float oxygenValue = hundredplac * 100 + tenplac * 10 + onesplac + miplac/10;
        oxygenStr = "" + oxygenValue;

        logger.debug("打印氧气浓度:"+oxygenStr);
        return 0;
    }
    //解析-臭氧浓度
//    private static int decodeoxygen(int infomt) {
//        logger.debug("oxygen值:" + infomt);
//        String oxygenStr = "";
//        int byte1 = (infomt >> 8) & 0xFF;
//        int byte2 = infomt & 0xFF;
//
//        int hundredplac = (byte1 >> 4) & 0x0F;
//        logger.debug("hundredplac固定值:"+ hundredplac);
//        hundredplac = 0;
//        int tenplac = byte1 & 0x0F;
//        int onesplac = (byte2 >> 4) & 0x0F;
//        int miplac = byte2 & 0x0F;
//
//        float oxygenValue = hundredplac * 100 + tenplac * 10 + onesplac + miplac/10;
//        oxygenStr = "" + oxygenValue;
//
//        logger.debug("打印氧气浓度:"+oxygenStr);
//        return 0;
//    }
    //解析-环境参数越限状态
    //    private static int decodeoxygen(int infomt) {
//        logger.debug("oxygen值:" + infomt);
//        String oxygenStr = "";
//        int byte1 = (infomt >> 8) & 0xFF;
//        int byte2 = infomt & 0xFF;
//
//        int hundredplac = (byte1 >> 4) & 0x0F;
//        logger.debug("hundredplac固定值:"+ hundredplac);
//        hundredplac = 0;
//        int tenplac = byte1 & 0x0F;
//        int onesplac = (byte2 >> 4) & 0x0F;
//        int miplac = byte2 & 0x0F;
//
//        float oxygenValue = hundredplac * 100 + tenplac * 10 + onesplac + miplac/10;
//        oxygenStr = "" + oxygenValue;
//
//        logger.debug("打印氧气浓度:"+oxygenStr);
//        return 0;
//    }
    //蓄水池水位
    //    private static int decodeoxygen(int infomt) {
//        logger.debug("oxygen值:" + infomt);
//        String oxygenStr = "";
//        int byte1 = (infomt >> 8) & 0xFF;
//        int byte2 = infomt & 0xFF;
//
//        int hundredplac = (byte1 >> 4) & 0x0F;
//        logger.debug("hundredplac固定值:"+ hundredplac);
//        hundredplac = 0;
//        int tenplac = byte1 & 0x0F;
//        int onesplac = (byte2 >> 4) & 0x0F;
//        int miplac = byte2 & 0x0F;
//
//        float oxygenValue = hundredplac * 100 + tenplac * 10 + onesplac + miplac/10;
//        oxygenStr = "" + oxygenValue;
//
//        logger.debug("打印氧气浓度:"+oxygenStr);
//        return 0;
//    }
    //时钟6字节

    public static long parseLong(String s, int radix) throws NumberFormatException {
        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX");
        }
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX");
        }

        long result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        long limit = -Long.MAX_VALUE;
        long multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Long.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }
}

class NumberFormatException extends IllegalArgumentException {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public NumberFormatException(String s) {
        super(s);
    }

    static NumberFormatException forInputString(String s) {
        return new NumberFormatException("For input string: \"" + s + "\"");
    }
}
